/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: KlineActivity.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.kline.ui;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Pair;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bhex.enums.INDEX_TYPE;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import io.bhex.app.R;
import io.bhex.app.ScreenShot.BitmapUtils;
import io.bhex.app.ScreenShot.IScreenshotCallBack;
import io.bhex.app.ScreenShot.MediaContentCallback;
import io.bhex.app.ScreenShot.MediaContentObserver;
import io.bhex.app.ScreenShot.ShotScreenUtils;
import io.bhex.app.base.BaseActivity;
import io.bhex.app.event.PriceDigitsEvent;
import io.bhex.app.kline.bean.PriceDigits;
import io.bhex.app.kline.presenter.KlinePresenter;
import io.bhex.app.market.api.MarketApi;
import io.bhex.app.qrcode.zxing.QRCodeEncoder;
import io.bhex.app.share.SHARE_MEDIA;
import io.bhex.app.share.ShareUtils;
import io.bhex.app.share.SystemShareUtils;
import io.bhex.app.utils.AnimalUtils;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.DialogUtils;
import io.bhex.app.utils.KlineUtils;
import io.bhex.app.utils.NumberUtils;
import io.bhex.app.utils.ShareConfigUtils;
import io.bhex.app.utils.SkinColorUtil;
import io.bhex.app.view.NoScrollViewPager;
import io.bhex.app.view.PopWindowList;
import io.bhex.app.view.TopBar;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.baselib.utils.ImageUtils;
import io.bhex.baselib.utils.PixelUtils;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.sdk.config.bean.ShareConfigBean;
import io.bhex.sdk.data_manager.AssetUtilsManager;
import io.bhex.sdk.data_manager.RateAndLocalManager;
import io.bhex.sdk.data_manager.RateDataManager;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.enums.COIN_TYPE;
import io.bhex.sdk.invite.bean.InviteResponse;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.sdk.quote.bean.OptionSymbolStatusBean;
import io.bhex.sdk.quote.bean.TickerBean;
import io.bhex.sdk.trade.OptionApi;
import pub.devrel.easypermissions.EasyPermissions;

public class KlineActivity extends BaseActivity<KlinePresenter, KlinePresenter.KlineUI> implements KlinePresenter.KlineUI, View.OnClickListener, AssetUtilsManager.IndexChangeInterface, IScreenshotCallBack,EasyPermissions.PermissionCallbacks {

    private static final float HEIGHT_ENTRUST_HEADER = 40f;//委托单头部高度
    private static final float HEIGHT_LATEST_HEADER = 40f;//最新成交头部高度
    private static final float VIEWPAGER_KLINE_HEIGHT_DEFAULT = 300f;//k线图viewpager竖屏默认高度  横屏高度为全屏高度-状态栏高度
    private static final int WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE = 2;
    private TopBar topBar;
    private NoScrollViewPager viewPagerKline;
    private NoScrollViewPager viewPager;
    private TabLayout tab;
    private List<Pair<String, Fragment>> items;
    private List<Pair<String, Fragment>> itemsKline;
    private String coinPair = "";//币对
    private KlineFragment klineFragment;
    private View topMarketView;
    private View topOptionView;
    private View topMarketViewLand;
    private View buysellLinear;
    private LinearLayout entrustHeader;
    private LinearLayout latestHeader;
    private AppBarLayout appBar;
    private int appBarHeight;
    LinearLayout.LayoutParams appBarLayoutParams;
    private int currentOrderTabPosition;//当前选择的订单tab
    private boolean forbidAppBarScroll;//是否禁止滑动appbar
    RelativeLayout.LayoutParams layoutParamsViewPagerKline;
    RelativeLayout.LayoutParams tabLinear1LayoutParams;
    private RelativeLayout tabLinear;
    private LinearLayout tabLinear1;
    private BookListFragment bookListFragment;
    List<PriceDigits.DigitsItem> digitsList = new ArrayList<>();
    //是否显示着K线Tab图
    private LinearLayout klineLinear;
    //    private boolean isShowKlineTab = false;
    //private RelativeLayout klineTabRela;
    private LayoutInflater layoutInflater;
    private View marketDividerView;
    private TickerBean currentTicker;
    private String exchangeId = "";
    //合并深度小数
    private String mergeDigitsStr = "";
    private boolean isFavorite;//是否是自选
    private int currentTabId = R.id.tab_kline_name;
    private final int CHART_TYPE_NOT_KLINE = -1;//不是K线chart
    private final int CHART_TYPE_KLINE = 0;//是K线chart
    private int CHART_TYPE = CHART_TYPE_NOT_KLINE;//不是K线chart
    //private int KLINE_TYPE_TIME=0x10;//分时
    //private int KLINE_TYPE_CANDLE=0x11;//蜡烛图
    //private int lastKlineType = KLINE_TYPE_CANDLE;//默认是蜡烛图 15分钟线
    private boolean currentShowKlineTab = false;//子K线选择Tab当前显示状态
    private int currentKlineType = KlineFragment.KLINE_TYPE_MINUTE_FIFTEEN;//默认15分钟线
    private String baseToken = "";
    private String quoteToken = "";
    private CoinPairBean coinPairBean;
    private View verticalScreen;
    private PopWindowList popListView;
    private View indexLandView;
    private View tabLandView;
    private View tabTime;
    //分钟线popup tab数组
    private String[] tabMinuteArray;
    private PopWindowList popTabListView;
    private TextView tabLandMinutes;
    private ImageView tabLandMinutesIcon;
    //是否是深度tab
    private boolean isDepthTab = false;
    //默认是竖屏
    private boolean isVerticalScreen = true;
    private String baseTokenName = "";
    private String quoteTokenName = "";
    private RelativeLayout.LayoutParams indexLandViewLayoutParams;
    private int baseDigit;
    private int quoteDigit;
    private boolean isDefaultSeeDepth;
    private boolean bShowIndex = false;

    private Timer timer;
    private TimerTask taskSettle;
    private TimerTask task;
    private static final int nPeriod = 1 * 1000;

    private Handler mHandler;
    private OptionSymbolStatusBean.OptionSymbolStatus mOptionSymbolStatus;
    private static final int TIMER_MESSAGE = 0X1;

    private static final int TIMER_SETTLE_MESSAGE = 0X2;
    private HandlerThread mHandlerThread;
    private MediaContentObserver mInternalObserver;
    private MediaContentObserver mExternalObserver;
    private ContentResolver mContentResolver;
    private IScreenshotCallBack mScreenshotCallBack;
    private Bitmap attachBitmap;
    private View shareView;
    private ImageView shareQrcodeImg;
    private View sharePreView;
    private ImageView sharePreViewImg;
    private String resultPath;
    private Bitmap resultBitmap;
    private Handler mShotHandler;
    private ShareConfigBean shareConfig;
    private ImageView shareLogoImg;
    private TextView shareName;
    private TextView shareDesp;
    private String shareUrl;

    @Override
    protected int getContentView() {
        return R.layout.activity_kline_layout;
    }

    @Override
    protected KlinePresenter createPresenter() {
        return new KlinePresenter(this);
    }

    @Override
    protected KlinePresenter.KlineUI getUI() {
        return this;
    }

    @Override
    protected void initView() {
        super.initView();
        topBar = viewFinder.find(R.id.topBar);
        this.setTopbarNight(topBar);
        //topBar收藏按钮
        ImageView favoriteImg = topBar.getRightImg();
        //topBar分享按钮
        ImageView rightImg2 = topBar.getRightImg2();
        rightImg2.setVisibility(View.VISIBLE);
        rightImg2.setImageResource(R.mipmap.icon_go_share);
        rightImg2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shotScreenShare();
            }
        });


        Intent intent = getIntent();
        if (intent != null) {
            isDefaultSeeDepth = intent.getBooleanExtra(AppData.INTENT.DEPTHVIEW, false);
            coinPairBean = (CoinPairBean) intent.getSerializableExtra(AppData.INTENT.SYMBOLS);
//            String symbolId = intent.getStringExtra(AppData.INTENT.SYMBOLS);
//            coinPairBean = SymbolDataManager.GetInstance().getSymbolInfoById(symbolId);
            if (coinPairBean != null) {
                coinPair = coinPairBean.getSymbolId();
                exchangeId = coinPairBean.getExchangeId();
                mergeDigitsStr = coinPairBean.getDigitMerge();
                isFavorite = SymbolDataManager.GetInstance().isFavorite(coinPairBean);
                baseToken = coinPairBean.getBaseTokenId();
                quoteToken = coinPairBean.getQuoteTokenId();
                baseDigit = SymbolDataManager.GetInstance().getTokenDigitBySymbolIdAndTokenId(coinPairBean.getSymbolId() + baseToken);
                quoteDigit = SymbolDataManager.GetInstance().getTokenDigitBySymbolIdAndTokenId(coinPairBean.getSymbolId() + quoteToken);
                baseTokenName = coinPairBean.getBaseTokenName();
                quoteTokenName = coinPairBean.getQuoteTokenName();

                //委托 最新成交 title设置
                viewFinder.textView(R.id.title_buy_amount).setText(String.format(getString(R.string.string_amount_buy_ph), baseTokenName));
                viewFinder.textView(R.id.title_sell_amount).setText(String.format(getString(R.string.string_amount_sell_ph), baseTokenName));
                viewFinder.textView(R.id.title_price).setText(String.format(getString(R.string.string_price_ph), quoteTokenName));
                viewFinder.textView(R.id.title_deal_price).setText(String.format(getString(R.string.string_price_ph), quoteTokenName));
                viewFinder.textView(R.id.title_deal_amount).setText(String.format(getString(R.string.string_deal_amount_format), baseTokenName));

                if (KlineUtils.isSymbolOfBB(coinPairBean.getCoinType())) {
                    //币币
                    if (!TextUtils.isEmpty(coinPair)) {
                        topBar.setTitle(coinPairBean.getBaseTokenName() + "/" + coinPairBean.getQuoteTokenName());
                    }
                    ((TextView) findViewById(R.id.coinPairName)).setText(baseTokenName + "/" + quoteTokenName); //横屏sybolName

                    //币币收藏按钮
                    favoriteImg.setVisibility(View.VISIBLE);
                    topBar.setRightImg(isFavorite ? R.mipmap.icon_favorite_checked : R.mipmap.icon_favorite);
                    topBar.setRightOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (!TextUtils.isEmpty(coinPair) && !TextUtils.isEmpty(exchangeId)) {
                                MarketApi.favoriteCoin(KlineActivity.this, coinPairBean, new MarketApi.CallBack() {
                                    @Override
                                    public void success(Object obj) {
                                        isFavorite = !isFavorite;
                                        coinPairBean.setFavorite(isFavorite);
                                        SymbolDataManager.GetInstance().cancelLocalFavorite(coinPairBean);
                                        SymbolDataManager.GetInstance().getSymbolInfoById(coinPair).setFavorite(isFavorite);
                                        topBar.setRightImg(isFavorite ? R.mipmap.icon_favorite_checked : R.mipmap.icon_favorite);
                                        KlineUtils.saveFavorite(coinPairBean);
                                    }

                                    @Override
                                    public void failed() {

                                    }
                                });
                            }
                        }
                    });

                    //顶部最新价等指标
                    viewFinder.find(R.id.top_market_data).setVisibility(View.VISIBLE); //币币
                    viewFinder.find(R.id.top_option_data).setVisibility(View.GONE);  //期权

                } else if (KlineUtils.isSymbolOfOption(coinPairBean.getCoinType())) {
                    //期权

                    favoriteImg.setVisibility(View.GONE);
                    topBar.setTitle(coinPairBean.getSymbolName());
                    ((TextView) findViewById(R.id.coinPairName)).setText(coinPairBean.getSymbolName()); //横屏sybolName
                    if (coinPairBean.baseTokenOption != null && !TextUtils.isEmpty(coinPairBean.getSymbolName()) && !TextUtils.isEmpty(coinPairBean.baseTokenOption.isCall)) {
                        String call = "";
                        if (KlineUtils.isOptionCall(coinPairBean.baseTokenOption.isCall)) {
                            call = getString(R.string.string_option_call);
                            topBar.setLeftTextAndBackGround(call, R.style.Mini_Green, R.drawable.bg_corner_rect_green);
                        } else {
                            call = getString(R.string.string_option_put);
                            topBar.setLeftTextAndBackGround(call, R.style.Mini_Red, R.drawable.bg_corner_rect_red);
                        }
                        topBar.setTitle(coinPairBean.getSymbolName());
                        topBar.setTitleAppearance(R.style.BodyL_Dark_Bold);
                        //topBar.setTitleLength(180);
                    }

                    viewFinder.textView(R.id.title_buy_amount).setText(String.format(getString(R.string.string_amount_buy_ph), getString(R.string.string_option_unit)));
                    viewFinder.textView(R.id.title_sell_amount).setText(String.format(getString(R.string.string_amount_sell_ph), getString(R.string.string_option_unit)));
                    viewFinder.textView(R.id.title_deal_amount).setText(String.format(getString(R.string.string_deal_amount_format), getString(R.string.string_option_unit)));

                    //买卖按钮
                    //viewFinder.textView(R.id.btn_buy).setText(getString(R.string.string_purchase) + "(" + getString(R.string.string_option_purchase) + ")");
                    //viewFinder.textView(R.id.btn_sell).setText(getString(R.string.string_sellout) + "(" + getString(R.string.string_option_sellout) + ")");
                    viewFinder.textView(R.id.btn_buy).setText(getString(R.string.string_purchase));
                    viewFinder.textView(R.id.btn_sell).setText(getString(R.string.string_sellout));
                    //顶部最新价等指标
                    viewFinder.find(R.id.top_market_data).setVisibility(View.GONE); //币币
                    viewFinder.find(R.id.top_option_data).setVisibility(View.VISIBLE);  //期权

                } else if (KlineUtils.isSymbolOfFutures(coinPairBean.getCoinType())) {
                    //合约

                    favoriteImg.setVisibility(View.GONE);
                    topBar.setTitle(coinPairBean.getSymbolName());
                    ((TextView) findViewById(R.id.coinPairName)).setText(coinPairBean.getSymbolName()); //横屏sybolName

                    viewFinder.textView(R.id.title_buy_amount).setText(String.format(getString(R.string.string_amount_buy_ph), getString(R.string.string_option_unit)));
                    viewFinder.textView(R.id.title_sell_amount).setText(String.format(getString(R.string.string_amount_sell_ph), getString(R.string.string_option_unit)));
                    viewFinder.textView(R.id.title_deal_amount).setText(String.format(getString(R.string.string_deal_amount_format), getString(R.string.string_option_unit)));

                    //顶部最新价等指标
                    viewFinder.find(R.id.top_market_data).setVisibility(View.VISIBLE); //币币
                    viewFinder.find(R.id.top_option_data).setVisibility(View.GONE);  //期权
                    //买卖按钮
                    viewFinder.textView(R.id.btn_buy).setText(getString(R.string.string_purchase) + "(" + getString(R.string.string_futures_open_long) + ")");
                    viewFinder.textView(R.id.btn_sell).setText(getString(R.string.string_sellout) + "(" + getString(R.string.string_futures_open_short) + ")");
                }

            } else {
//                ToastUtils.showShort(getString(R.string.string_net_exception));
            }

        }


        tabMinuteArray = new String[]{getResources().getString(R.string.kline_thirty_minutes), getResources().getString(R.string.kline_fifteen_minutes), getResources().getString(R.string.kline_five_minutes), getResources().getString(R.string.kline_one_minute)};

        appBar = viewFinder.find(R.id.appBar);

        appBarLayoutParams = (LinearLayout.LayoutParams) appBar.getLayoutParams();
        appBarHeight = appBarLayoutParams.height;
        appBarLayoutParams.height = appBarHeight + PixelUtils.dp2px(HEIGHT_ENTRUST_HEADER);
        appBar.setLayoutParams(appBarLayoutParams);
        klineLinear = viewFinder.find(R.id.kline_linear);
        layoutInflater = LayoutInflater.from(this);
        //
        //横屏ticker
        topMarketViewLand = layoutInflater.inflate(R.layout.include_latest_market_header_land_layout, klineLinear, false);
        verticalScreen = topMarketViewLand.findViewById(R.id.tab_verticalscreen);
        //klineTabRela = (RelativeLayout) klineLinear.getChildAt(3);
        //竖屏ticker
        topMarketView = viewFinder.find(R.id.top_market_data);
        topOptionView = viewFinder.find(R.id.top_option_data);
        marketDividerView = viewFinder.find(R.id.market_divider);
        //横屏指标切换按钮
        indexLandView = viewFinder.find(R.id.index_land_layout);
        indexLandViewLayoutParams = (RelativeLayout.LayoutParams) indexLandView.getLayoutParams();
        //横屏tab
        tabLandView = layoutInflater.inflate(R.layout.kline_tab_land_layout, klineLinear, false);
        tabLandMinutes = tabLandView.findViewById(R.id.tab_land_minutes);
        tabLandMinutesIcon = tabLandView.findViewById(R.id.tab_land_selctec_icon);

        viewPagerKline = viewFinder.find(R.id.viewPagerKline);
        viewPagerKline.setScanScroll(false);
        layoutParamsViewPagerKline = (RelativeLayout.LayoutParams) viewPagerKline.getLayoutParams();
        viewPager = viewFinder.find(R.id.viewPager);
        viewPager.setScanScroll(false);//设置不可以滑动切换页
        tab = viewFinder.find(R.id.tab);
        tab.setTabTextColors(SkinColorUtil.getDark(this), getResources().getColor(R.color.blue));
        buysellLinear = viewFinder.find(R.id.buysell_linear);
        entrustHeader = viewFinder.find(R.id.entrust_header);
        latestHeader = viewFinder.find(R.id.latest_header);
        tabLinear = viewFinder.find(R.id.tabLinear);
        tabLinear1 = viewFinder.find(R.id.tabLinear1);
        //tabLinear1.setBackgroundResource(CommonUtil.isBlackMode()?R.mipmap.icon_pop_bg_big_night:R.mipmap.icon_pop_bg_big);
        tabLinear1LayoutParams = (RelativeLayout.LayoutParams) tabLinear1.getLayoutParams();

        //kline

        initKlineFragmentTab();
        initOrderFragmentTab();
        klineTabMap.put(R.id.tab_minute_fifteen, viewFinder.textView(R.id.tab_minute_fifteen));
        landTabMap.put(R.id.tab_land_15m, (TextView) tabLandView.findViewById(R.id.tab_land_15m));

        swtichIndexTab(R.id.tab_ma, R.id.tab_land_ma);
        swtichSubIndexTab(R.id.tab_vol, R.id.tab_land_vol);

        ((TextView) (tabLandView.findViewById(R.id.tab_land_15m))).setTextColor(getResources().getColor(R.color.blue));
        ((TextView) (viewFinder.find(R.id.tab_minute_fifteen))).setTextColor(getResources().getColor(R.color.blue));

        if (KlineUtils.isSymbolOfOption(coinPairBean.getCoinType())) {
            //期权
            viewFinder.textView(R.id.option_exercise_point_title).setText(getString(R.string.string_exercise_point) + "(" + quoteTokenName + ")");
            viewFinder.textView(R.id.option_exercise_price_title).setText(getString(R.string.string_exercise_price) + "(" + quoteTokenName + ")");
            viewFinder.textView(R.id.option_maxPayOff_title).setText(getString(R.string.string_option_maxPayOff)/* + "(" + quoteTokenName + "/"+ getString(R.string.string_option_unit)+")"*/);
            viewFinder.textView(R.id.option_exercise_price).setText(coinPairBean.baseTokenOption.strikePrice);
            viewFinder.textView(R.id.option_maxPayOff).setText(coinPairBean.baseTokenOption.maxPayOff);
        } else if (KlineUtils.isSymbolOfFutures(coinPairBean.getCoinType())) {
            //合约
        } else {
//            viewFinder.find(R.id.top_market_data).setVisibility(View.VISIBLE);
//            viewFinder.find(R.id.top_option_data).setVisibility(View.GONE);
        }

        if (coinPairBean != null) {
            if (coinPairBean.getCoinType() == COIN_TYPE.COIN_TYPE_PERPETUAL_CONTRACT.getCoinType()) {//合约
                viewFinder.textView(R.id.btn_buy).setText(getString(R.string.string_purchase) + "(" + getString(R.string.string_futures_open_long) + ")");
                viewFinder.textView(R.id.btn_sell).setText(getString(R.string.string_sellout) + "(" + getString(R.string.string_futures_open_short) + ")");
            }
        }

        //分享view初始化
        shareView = layoutInflater.inflate(R.layout.flater_share_qrcode_layout, null, false);
        shareLogoImg = shareView.findViewById(R.id.logo);
        shareName = shareView.findViewById(R.id.name);
        shareDesp = shareView.findViewById(R.id.desp);
        shareQrcodeImg = shareView.findViewById(R.id.qrcode);
        sharePreView = viewFinder.find(R.id.preView);
        sharePreViewImg = viewFinder.imageView(R.id.preViewImg);
        ShareConfigBean shareConfig = ShareConfigUtils.getShareConfig();
        setShareConfig(shareConfig);


        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                // 指数 时间

                mHandler.sendEmptyMessage(TIMER_MESSAGE);
            }
        };
        if (KlineUtils.isSymbolOfOption(coinPairBean.getCoinType())) {
            //期权   交割状态定时刷新
            timer.schedule(task, 50, nPeriod);
            taskSettle = new TimerTask() {
                @Override
                public void run() {
                    long time = Long.valueOf(coinPairBean.baseTokenOption.settlementDate) - System.currentTimeMillis();
                    if (mOptionSymbolStatus != null && mOptionSymbolStatus.settleStatus != null && mOptionSymbolStatus.settleStatus.equalsIgnoreCase("SETTLE_DONE")) {

                    } else if (time <= 0) {
                        mHandler.sendEmptyMessage(TIMER_SETTLE_MESSAGE);
                    }
                }
            };

            timer.schedule(taskSettle, 50, nPeriod * 6);
        }
    }

    private void stopSettleTimer() {
        if (taskSettle != null) {
            taskSettle.cancel();
        }
    }

    @Override
    public void setShareConfig(ShareConfigBean response) {
        if (response != null) {
            shareConfig = response;
            if (shareConfig != null) {
                shareName.setText(response.getTitle());
                shareDesp.setText(response.getDescription());
                String logoUrl = response.getLogoUrl();
                String openUrl = response.getOpenUrl();
                //TextUtils.isEmpty(openUrl);
                //CImageLoader.getInstance().load(shareLogoImg, logoUrl);
            }
        }
    }

    @Override
    public void showShareInfo(InviteResponse response) {
        if (response != null) {
            shareUrl = response.getShareUrl();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
//        if (!TextUtils.isEmpty(coinPair)) {
//
////            getPresenter().getTicker(exchangeId, coinPair);
////            getPresenter().requestDepthData(exchangeId, coinPair, Integer.valueOf(AppData.TICKER.LIMIT_DEPTH));
//
//            //打开默认K线
//            appBar.postDelayed(new Runnable() {
//                @Override
//                public void run() {
////                    switchDefaultKline(currentKlineType);
//                }
//            }, 1000);
//
//        } else {
////            ToastUtils.showShort("coinPair is null");
//        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case TIMER_MESSAGE:
                        try {

                            if (coinPairBean != null && coinPairBean.baseTokenOption != null) {
                                if (mOptionSymbolStatus != null && mOptionSymbolStatus.settleStatus != null && (mOptionSymbolStatus.settleStatus.equalsIgnoreCase("SETTLE_DOING") || mOptionSymbolStatus.settleStatus.equalsIgnoreCase("SETTLE_DONE"))) {

                                    viewFinder.textView(R.id.option_exercise_point_title).setText(getString(R.string.string_option_delivery_price));
                                    if (mOptionSymbolStatus.settleDetail != null && !TextUtils.isEmpty(mOptionSymbolStatus.settleDetail.settlementPrice)) {
                                        String price = NumberUtils.roundFormatDown(mOptionSymbolStatus.settleDetail.settlementPrice, SymbolDataManager.GetInstance().getTokenDigitBySymbolIdAndTokenId(coinPairBean.getSymbolId() + quoteToken));
                                        viewFinder.textView(R.id.option_exercise_point).setText(price);
                                    } else
                                        viewFinder.textView(R.id.option_exercise_point).setText("--");
                                } else {
                                    viewFinder.textView(R.id.option_exercise_point_title).setText(getString(R.string.string_exercise_point));
                                    String indexData = NumberUtils.roundFormatDown(AssetUtilsManager.GetInstance().getSymbolIndexOfOption(coinPairBean.baseTokenOption.indexToken), SymbolDataManager.GetInstance().getTokenDigitBySymbolIdAndTokenId(coinPairBean.getSymbolId() + quoteToken));
                                    viewFinder.textView(R.id.option_exercise_point).setText(indexData);
                                }
                            } else
                                viewFinder.textView(R.id.option_exercise_point).setText("--");

                            if (coinPairBean.baseTokenOption != null) {
                                long time = Long.valueOf(coinPairBean.baseTokenOption.settlementDate) - System.currentTimeMillis();
                                if (time <= 0) {
                                    if (mOptionSymbolStatus != null && mOptionSymbolStatus.settleStatus != null && mOptionSymbolStatus.settleStatus.equalsIgnoreCase("SETTLE_DONE"))
                                        viewFinder.textView(R.id.option_delivery_time).setText(getString(R.string.string_option_over_delivery));
                                    else
                                        viewFinder.textView(R.id.option_delivery_time).setText(getString(R.string.string_option_over_deliverying));
                                } else {
                                    int day = Math.round(time / 1000 / 60 / 60 / 24);
                                    // 时
                                    int hour = Math.round(time / 1000 / 60 / 60 % 24);
                                    // 分
                                    int minute = Math.round(time / 1000 / 60 % 60);
                                    // 秒
                                    int second = Math.round(time / 1000 % 60);

                                    if (day > 0)
                                        viewFinder.textView(R.id.option_delivery_time).setText(getString(R.string.string_option_delivery_timer) + day + getString(R.string.string_option_d));
                                    else
                                        viewFinder.textView(R.id.option_delivery_time).setText(getString(R.string.string_option_delivery_timer) + String.format(getString(R.string.string_option_h_m_s), hour, minute, second));
                                }
                            }
                        } catch (Exception e) {

                        }

                        break;
                    case TIMER_SETTLE_MESSAGE:
                        getSettleStatus();
                        break;
                }
            }
        };

        init(getContentResolver(), this);
        register();
    }

    /**
     * 自己：截屏分享
     */
    private void shotScreenShare() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
        if (!EasyPermissions.hasPermissions(this, perms)) {
            EasyPermissions.requestPermissions(this, getString(R.string.file_read_write_permission_hint), WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE, perms);
            return;
        }
        //弹出分享对话框
        shareDialogAction();

    }

    /**
     * 分享对话框的弹出
     */
    private void shareDialogAction(){
        Bitmap bitmap = ShotScreenUtils.shotScreen(KlineActivity.this);
        if (bitmap != null) {
//                if (CommonUtil.isBhex(this)) {

            if (shareConfig != null && !TextUtils.isEmpty(shareConfig.getOpenUrl())) {
                //此处调整为 邀请地址不为空 用邀请地址，为空则用后端shareConfig配置地址
                Bitmap bitmapQR = QRCodeEncoder
                        .syncEncodeQRCode(TextUtils.isEmpty(shareUrl)?shareConfig.getOpenUrl():shareUrl,
                                PixelUtils.dp2px(50),
                                SkinColorUtil.getDefaultDark(this),
                                SkinColorUtil.getDefaultWhite(this),
                                BitmapUtils.getBitmapByres(KlineActivity.this, R.mipmap.ic_launcher));
                shareQrcodeImg.setImageBitmap(bitmapQR);

                BitmapUtils.saveBitmap(KlineActivity.this,bitmapQR);

                attachBitmap = BitmapUtils.createBitmap3(shareView,
                        isVerticalScreen ?
                                PixelUtils.getScreenWidth() : (
                                PixelUtils.getScreenWidth() > PixelUtils.getScreenHeight() ?
                                        PixelUtils.getScreenWidth() : PixelUtils.getScreenHeight()),
                        PixelUtils.dp2px(80));

                BitmapUtils.saveBitmap(KlineActivity.this,attachBitmap);

                resultBitmap = BitmapUtils.concatBitmap(KlineActivity.this, isVerticalScreen, bitmap, attachBitmap);

                //      sharePreViewImg.setBackground(new BitmapDrawable(getResources(),resultBitmap));
                resultPath = BitmapUtils.saveBitmap(KlineActivity.this,resultBitmap);

                showShare(resultPath, resultBitmap);

            } else {
                resultPath = BitmapUtils.saveBitmap(KlineActivity.this,bitmap);

                showShare(resultPath, bitmap);
            }
        }
    }

    @Override
    public void screenshotTaken(final String path) {
        shotScreenShare();
//        Bitmap bitmap = QRCodeEncoder.syncEncodeQRCode("https://www.bhex.com/download.html", PixelUtils.dp2px(60), getResources().getColor(R.color.blue), getResources().getColor(R.color.white), BitmapUtils.getBitmapByres(this, R.mipmap.ic_launcher));
//        shareQrcodeImg.setImageBitmap(bitmap);
//        attachBitmap = BitmapUtils.createBitmap3(shareView, PixelUtils.getScreenWidth(), PixelUtils.dp2px(80));
//        resultBitmap = BitmapUtils.concatBitmap(KlineActivity.this, path, attachBitmap);
//
////        sharePreViewImg.setBackground(new BitmapDrawable(getResources(),resultBitmap));
//        resultPath = BitmapUtils.saveBitmap(resultBitmap);
//
//        showShare(resultPath);


    }

    private void showShare(final String resultPath, final Bitmap resultBitmap) {
        DialogUtils.showShareDialogOneBtn(this, "", resultPath, true,new DialogUtils.OnShareListener() {
            @Override
            public void onShareWx() {
                ShareUtils.share(SHARE_MEDIA.WEIXIN, resultBitmap);

            }

            @Override
            public void onShareWxCircle() {
                ShareUtils.share(SHARE_MEDIA.WEIXIN_CIRCLE, resultBitmap);
            }

            @Override
            public void onSavePic() {
                ImageUtils.saveImageToGallery(KlineActivity.this, resultBitmap);

//                String path = BitmapUtils.saveBitmap(resultBitmap);
//                ShotScreenUtils.AlbumScan(KlineActivity.this,resultPath);
                ToastUtils.showShort(getString(R.string.string_save_success));
            }

            @Override
            public void onMore() {
                SystemShareUtils.shareImage(KlineActivity.this,resultPath);
            }

            @Override
            public void onCancel() {

            }
        });

    }

    /**
     * 初始化监听
     *
     * @param contentResolver
     * @param screenshotCallBack
     */
    public void init(ContentResolver contentResolver, IScreenshotCallBack screenshotCallBack) {
        mContentResolver = contentResolver;
        mScreenshotCallBack = screenshotCallBack;
        mHandlerThread = new HandlerThread("Screenshot_Observer");
        mHandlerThread.start();
        mShotHandler = new Handler(mHandlerThread.getLooper());

        // 初始化
        mInternalObserver = new MediaContentObserver(MediaStore.Images.Media.INTERNAL_CONTENT_URI, mShotHandler, new MediaContentCallback() {
            @Override
            public void onChange(Uri contentUri, boolean selfChange) {
                handleMediaContentChange(contentUri);
            }
        });
        mExternalObserver = new MediaContentObserver(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, mShotHandler, new MediaContentCallback() {
            @Override
            public void onChange(Uri contentUri, boolean selfChange) {
                handleMediaContentChange(contentUri);
            }
        });
    }

    // 添加监听
    public void register() {
        mContentResolver.registerContentObserver(
                MediaStore.Images.Media.INTERNAL_CONTENT_URI,
                false,
                mInternalObserver
        );
        mContentResolver.registerContentObserver(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                false,
                mExternalObserver
        );
    }

    // 注销监听 ondestroy()
    public void unregister() {
        mContentResolver.unregisterContentObserver(mInternalObserver);
        mContentResolver.unregisterContentObserver(mExternalObserver);
    }

    private static final String[] KEYWORDS = {
            "screenshot", "screen_shot", "screen-shot", "screen shot",
            "screencapture", "screen_capture", "screen-capture", "screen capture",
            "screencap", "screen_cap", "screen-cap", "screen cap"
    };

    /**
     * 读取媒体数据库时需要读取的列
     */
    private static final String[] MEDIA_PROJECTIONS = {
            MediaStore.Images.ImageColumns.DATA,
            MediaStore.Images.ImageColumns.DATE_TAKEN,
    };

    private void handleMediaContentChange(Uri contentUri) {
        Cursor cursor = null;
        try {
            // 数据改变时查询数据库中最后加入的一条数据
            cursor = this.getContentResolver().query(
                    contentUri,
                    MEDIA_PROJECTIONS,
                    null,
                    null,
                    MediaStore.Images.ImageColumns.DATE_ADDED + " desc limit 1"
            );

            if (cursor == null) {
                return;
            }
            if (!cursor.moveToFirst()) {
                return;
            }

            // 获取各列的索引
            int dataIndex = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            int dateTakenIndex = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATE_TAKEN);

            // 获取行数据
            String data = cursor.getString(dataIndex);
            long dateTaken = cursor.getLong(dateTakenIndex);

            // 处理获取到的第一行数据
            handleMediaRowData(data, dateTaken);

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
        }
    }

    /**
     * 处理监听到的资源
     */
    private void handleMediaRowData(String data, long dateTaken) {
        long duration = 0;
        long step = 100;
        //设置最大等待时间为 500ms 手机保存会有延迟
        while (!checkScreenShot(data, dateTaken) && duration <= 500) {
            try {
                duration += step;
                Thread.sleep(step);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        if (checkScreenShot(data, dateTaken)) {
            DebugLog.d("screenshot", data + " " + dateTaken);
            if (mScreenshotCallBack != null) {
                mScreenshotCallBack.screenshotTaken(data);
            }
        } else {
            DebugLog.d("screenshot", "Not screenshot event");
        }
    }

    /**
     * 判断是否是截屏
     */
    private boolean checkScreenShot(String data, long dateTaken) {
        if (data == null) {
            return false;
        }

        data = data.toLowerCase();
        // 判断图片路径是否含有指定的关键字之一, 如果有, 则认为当前截屏了
        for (String keyWork : KEYWORDS) {
            if (data.contains(keyWork)) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (coinPairBean != null && coinPairBean.baseTokenOption != null) {

            AssetUtilsManager.GetInstance().AddIndexObserver(this);
        }
//        viewPagerKline.setCurrentItem(1);//默认深度图
        //默认是15分钟线
//        switchKline(R.id.tab_kline_name,KlineFragment.KLINE_TYPE_MINUTE_FIFTEEN);

    }

    @Override
    protected void onPause() {
        super.onPause();
        AssetUtilsManager.GetInstance().removeIndexObserver(this);
    }


    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (task != null) {
            task.cancel();
        }
        if (taskSettle != null) {
            taskSettle.cancel();
        }

        if (timer != null) {
            timer.purge();
            timer.cancel();
        }
        unregister();
    }

    @Override
    protected void addEvent() {
        super.addEvent();
        viewFinder.find(R.id.tab_kline).setOnClickListener(this);
        viewFinder.find(R.id.tab_depth).setOnClickListener(this);
        viewFinder.find(R.id.tab_time).setOnClickListener(this);
        viewFinder.find(R.id.tab_minute).setOnClickListener(this);
        viewFinder.find(R.id.tab_minute_five).setOnClickListener(this);
        viewFinder.find(R.id.tab_minute_fifteen).setOnClickListener(this);
        viewFinder.find(R.id.tab_minute_thirty).setOnClickListener(this);
        viewFinder.find(R.id.tab_hour).setOnClickListener(this);
        viewFinder.find(R.id.tab_day).setOnClickListener(this);
        viewFinder.find(R.id.tab_week).setOnClickListener(this);
        viewFinder.find(R.id.tab_month).setOnClickListener(this);

        /*横屏tab***/
        tabLandView.findViewById(R.id.tab_land_time_rela).setOnClickListener(this);
        tabLandView.findViewById(R.id.tab_land_1m_rela).setOnClickListener(this);
        tabLandView.findViewById(R.id.tab_land_5m_rela).setOnClickListener(this);
        tabLandView.findViewById(R.id.tab_land_15m_rela).setOnClickListener(this);
        tabLandView.findViewById(R.id.tab_land_30m_rela).setOnClickListener(this);
        tabLandView.findViewById(R.id.tab_land_hour_rela).setOnClickListener(this);
        tabLandView.findViewById(R.id.tab_land_day_rela).setOnClickListener(this);
        tabLandView.findViewById(R.id.tab_land_week_rela).setOnClickListener(this);
        tabLandView.findViewById(R.id.tab_land_month_rela).setOnClickListener(this);
        tabLandView.findViewById(R.id.tab_land_index_rela).setOnClickListener(this);


        viewFinder.find(R.id.tab_ma).setOnClickListener(this);
        viewFinder.find(R.id.tab_ema).setOnClickListener(this);
        viewFinder.find(R.id.tab_boll).setOnClickListener(this);
        viewFinder.find(R.id.tab_vol).setOnClickListener(this);
        viewFinder.find(R.id.tab_macd).setOnClickListener(this);
        viewFinder.find(R.id.tab_kdj).setOnClickListener(this);
        viewFinder.find(R.id.tab_rsi).setOnClickListener(this);
        viewFinder.find(R.id.tab_sub_boll).setOnClickListener(this);
        viewFinder.find(R.id.tab_close_major).setOnClickListener(this);
        viewFinder.find(R.id.tab_close_sub).setOnClickListener(this);

        viewFinder.find(R.id.tab_land_ma).setOnClickListener(this);
        viewFinder.find(R.id.tab_land_ema).setOnClickListener(this);
        viewFinder.find(R.id.tab_land_boll).setOnClickListener(this);
        viewFinder.find(R.id.tab_land_vol).setOnClickListener(this);
        viewFinder.find(R.id.tab_land_macd).setOnClickListener(this);
        viewFinder.find(R.id.tab_land_kdj).setOnClickListener(this);
        viewFinder.find(R.id.tab_land_rsi).setOnClickListener(this);
        viewFinder.find(R.id.tab_land_sub_wr).setOnClickListener(this);
        viewFinder.find(R.id.tab_land_close_major).setOnClickListener(this);
        viewFinder.find(R.id.tab_land_close_sub).setOnClickListener(this);

        viewFinder.find(R.id.tab_fullscreen).setOnClickListener(this);
        verticalScreen.setOnClickListener(this);
        viewFinder.find(R.id.title_decimal_num).setOnClickListener(this);
        viewFinder.find(R.id.btn_buy).setOnClickListener(this);
        viewFinder.find(R.id.btn_sell).setOnClickListener(this);
        viewPagerKline.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        viewFinder.find(R.id.preView).setOnClickListener(this);
        viewFinder.find(R.id.preViewImg).setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        if (popTabListView != null) {
            popTabListView.closePop();
        }
        switch (v.getId()) {
            case R.id.preView:
            case R.id.preViewImg:
                sharePreView.setVisibility(View.GONE);
                break;
            case R.id.tab_ma:
            case R.id.tab_land_ma:
                //klineFragment.switchMainMa();
                swtichIndexTab(R.id.tab_ma, R.id.tab_land_ma);
                switchShowKlineTabView(false);
                break;
            case R.id.tab_ema:
            case R.id.tab_land_ema:
                klineFragment.switchIndex(INDEX_TYPE.INDEX_EMA);
                swtichIndexTab(R.id.tab_ema, R.id.tab_land_ema);
                switchShowKlineTabView(false);
                break;
            case R.id.tab_boll:
            case R.id.tab_land_boll:
                //klineFragment.switchMainBoll();
                swtichIndexTab(R.id.tab_boll, R.id.tab_land_boll);
                switchShowKlineTabView(false);
                break;
            case R.id.tab_close_major:
            case R.id.tab_land_close_major:
                //klineFragment.hideMainLine();
                swtichIndexTab(R.id.tab_close_major, R.id.tab_land_close_major);
                switchShowKlineTabView(false);
                break;

            //sub tab
            case R.id.tab_vol:
            case R.id.tab_land_vol:
                //klineFragment.switchIndex(INDEX_TYPE.INDEX_VOL);
                swtichSubIndexTab(R.id.tab_vol, R.id.tab_land_vol);
                switchShowKlineTabView(false);
                break;

            case R.id.tab_macd:
            case R.id.tab_land_macd:
                klineFragment.switchIndex(INDEX_TYPE.INDEX_MACD);
                swtichSubIndexTab(R.id.tab_macd, R.id.tab_land_macd);
                switchShowKlineTabView(false);
                break;

            case R.id.tab_kdj:
            case R.id.tab_land_kdj:
                klineFragment.switchIndex(INDEX_TYPE.INDEX_KDJ);
                swtichSubIndexTab(R.id.tab_kdj, R.id.tab_land_kdj);
                switchShowKlineTabView(false);
                break;

            case R.id.tab_rsi:
            case R.id.tab_land_rsi:
                klineFragment.switchIndex(INDEX_TYPE.INDEX_RSI);
                swtichSubIndexTab(R.id.tab_rsi, R.id.tab_land_rsi);
                switchShowKlineTabView(false);
                break;
            case R.id.tab_sub_boll:
            case R.id.tab_land_sub_wr:
                klineFragment.switchIndex(INDEX_TYPE.INDEX_BOLL);
                swtichSubIndexTab(R.id.tab_sub_boll, R.id.tab_land_sub_wr);
                switchShowKlineTabView(false);
                break;

            case R.id.tab_close_sub:
            case R.id.tab_land_close_sub:
                klineFragment.switchIndex(INDEX_TYPE.INDEX_VOL);
                swtichSubIndexTab(R.id.tab_close_sub, R.id.tab_land_close_sub);
                switchShowKlineTabView(false);
                break;

            //深度
            case R.id.tab_depth:
                switchKline(R.id.tab_depth, CHART_TYPE_NOT_KLINE);
                break;
            //K线图类型
            case R.id.tab_kline:
                switchKline(R.id.tab_kline, currentKlineType);
                break;
            case R.id.tab_time:
            case R.id.tab_land_time_rela:
                switchKline(R.id.tab_time, KlineFragment.KLINE_TYPE_TIME);
                swtichLandTab(R.id.tab_land_time);
                break;

            case R.id.tab_land_minutes:
                if (popTabListView == null) {
                    popTabListView = new PopWindowList(this, new PopWindowList.ListOnItemClick() {
                        @Override
                        public void onItemClick(String item, int layoutPosition) {
                            swtichLandTab(R.id.tab_land_minutes);
                            String tabName = tabMinuteArray[layoutPosition];
                            tabLandMinutes.setText(tabName);
                            switch (layoutPosition) {
                                case 0:
                                    //30分钟
//                                    swtichKlineTab(R.id.tab_minute_thirty);
                                    switchKline(R.id.tab_minute_thirty, KlineFragment.KLINE_TYPE_MINUTE_THIRTY);
                                    break;
                                case 1:
                                    //15分钟
//                                    swtichKlineTab(R.id.tab_minute_fifteen);
                                    switchKline(R.id.tab_minute_fifteen, KlineFragment.KLINE_TYPE_MINUTE_FIFTEEN);
                                    break;
                                case 2:
                                    //5分钟
//                                    swtichKlineTab(R.id.tab_minute_five);
                                    switchKline(R.id.tab_minute_five, KlineFragment.KLINE_TYPE_MINUTE_FIVE);
                                    break;
                                case 3:
                                    //1分钟
//                                    swtichKlineTab(R.id.tab_minute);
                                    switchKline(R.id.tab_minute, KlineFragment.KLINE_TYPE_MINUTE);
                                    break;
                            }
                        }
                    });
                }
                popTabListView.setAdapter(Arrays.asList(tabMinuteArray));
                popTabListView.setBackgroudRes(CommonUtil.isBlackMode() ? R.mipmap.icon_pop_bg_down_night : R.mipmap.icon_pop_bg_down, true);
                popTabListView.showPopList(tabLandMinutes, 0, -popTabListView.getHeight() - tabLandMinutes.getMeasuredHeight());
                break;
            case R.id.tab_minute:
            case R.id.tab_land_1m_rela:
                switchKline(R.id.tab_minute, KlineFragment.KLINE_TYPE_MINUTE);
                tabLandMinutes.setText(getString(R.string.kline_one_minute));
                swtichLandTab(R.id.tab_land_1m);
                break;
            case R.id.tab_minute_five:
            case R.id.tab_land_5m_rela:
                switchKline(R.id.tab_minute_five, KlineFragment.KLINE_TYPE_MINUTE_FIVE);
                tabLandMinutes.setText(getString(R.string.kline_five_minutes));
                swtichLandTab(R.id.tab_land_5m);
                break;
            case R.id.tab_minute_fifteen:
            case R.id.tab_land_15m_rela:
                switchKline(R.id.tab_minute_fifteen, KlineFragment.KLINE_TYPE_MINUTE_FIFTEEN);
                tabLandMinutes.setText(getString(R.string.kline_fifteen_minutes));
                swtichLandTab(R.id.tab_land_15m);
                break;
            case R.id.tab_minute_thirty:
            case R.id.tab_land_30m_rela:
                switchKline(R.id.tab_minute_thirty, KlineFragment.KLINE_TYPE_MINUTE_THIRTY);
                tabLandMinutes.setText(getString(R.string.kline_thirty_minutes));
                swtichLandTab(R.id.tab_land_30m);
                break;
            case R.id.tab_hour:
            case R.id.tab_land_hour_rela:
                switchKline(R.id.tab_hour, KlineFragment.KLINE_TYPE_HOUR_ONE);
                swtichLandTab(R.id.tab_land_hour);
                break;
            case R.id.tab_day:
            case R.id.tab_land_day_rela:
                switchKline(R.id.tab_day, KlineFragment.KLINE_TYPE_DAY_ONE);
                swtichLandTab(R.id.tab_land_day);
                break;
            case R.id.tab_week:
            case R.id.tab_land_week_rela:
                switchKline(R.id.tab_week, KlineFragment.KLINE_TYPE_WEEK_ONE);
                swtichLandTab(R.id.tab_land_week);
                break;
            case R.id.tab_month:
            case R.id.tab_land_month_rela:
                switchKline(R.id.tab_month, KlineFragment.KLINE_TYPE_MONTH_ONE);
                swtichLandTab(R.id.tab_land_month);
                break;
            case R.id.tab_land_index_rela:
                if (bShowIndex == false) {
                    bShowIndex = true;
                    ((TextView) (tabLandView.findViewById(R.id.tab_land_index))).setTextColor(getResources().getColor(R.color.blue));
                    indexLandView.setVisibility(View.VISIBLE);
                    ((ImageView) tabLandView.findViewById(R.id.tab_land_index_icon)).setImageResource(R.mipmap.icon_arrow_up_blue2);
                    AnimalUtils.rotateyAnimRun(tabLandView.findViewById(R.id.tab_land_index_icon), 0.0f, 180.0f);
                } else {
                    bShowIndex = false;
                    ((TextView) (tabLandView.findViewById(R.id.tab_land_index))).setTextColor(CommonUtil.isBlackMode() ? getResources().getColor(R.color.dark_night) : getResources().getColor(R.color.dark));
                    indexLandView.setVisibility(View.GONE);
                    ((ImageView) tabLandView.findViewById(R.id.tab_land_index_icon)).setImageResource(R.mipmap.icon_arrow_up_black);
                    AnimalUtils.rotateyAnimRun(tabLandView.findViewById(R.id.tab_land_index_icon), 180.0f, 0.0f);
                }
                break;

            case R.id.tab_fullscreen:
//                boolean isVertical = (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT);
//                if (isVertical) {
//                    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//                    viewFinder.textView(R.id.full_scrren_tx).setText(getString(R.string.kline_vertical_screen));
//                } else {
//                    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
//                    viewFinder.textView(R.id.full_scrren_tx).setText(getString(R.string.kline_full_screen));
//                }
                viewFinder.find(R.id.tab_fullscreen).setVisibility(View.GONE);
                verticalScreen.setVisibility(View.VISIBLE);
                this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                break;
            case R.id.tab_verticalscreen:
                viewFinder.find(R.id.tab_fullscreen).setVisibility(View.VISIBLE);
                verticalScreen.setVisibility(View.GONE);
                this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
                break;
            case R.id.title_decimal_num://委托订单-盘口小数
                if (!TextUtils.isEmpty(mergeDigitsStr)) {
                    String[] digitsArray = mergeDigitsStr.split(",");
                    if (digitsArray.length > 0) {
                        digitsList.clear();
                        for (String s : digitsArray) {
                            PriceDigits.DigitsItem digitsItem = new PriceDigits.DigitsItem();
                            String name = NumberUtils.calNumerName(this, s);
                            digitsItem.setDigitsName(name);
                            digitsItem.setDigits(s);
                            digitsList.add(digitsItem);
                        }
                        String[] itemNames = new String[digitsList.size()];
                        for (int i = 0; i < digitsList.size(); i++) {
                            itemNames[i] = digitsList.get(i).getDigitsName();
                        }
//                        new AlertView(getString(R.string.string_depth_digits), null, getString(R.string.string_cancel), null, itemNames, this, AlertView.Style.ActionSheet, this).show();
                        if (popListView == null) {
                            popListView = new PopWindowList(this, new PopWindowList.ListOnItemClick() {
                                @Override
                                public void onItemClick(String item, int layoutPosition) {
                                    String digits = digitsList.get(layoutPosition).getDigits();
//                                    ToastUtils.showShort(layoutPosition+" "+digits);F
                                    //深度小数通知
                                    EventBus.getDefault().post(new PriceDigitsEvent(digits));
                                    viewFinder.textView(R.id.title_decimal_num).setText(item);
                                }
                            });
                        }
                        popListView.setAdapter(Arrays.asList(itemNames));
                        popListView.setBackgroudRes(CommonUtil.isBlackMode() ? R.mipmap.icon_popup_bg_up_night : R.mipmap.icon_popup_bg_up, true);
                        popListView.showPopList(viewFinder.find(R.id.title_decimal_num), 0, 0);
                    }

                }

                break;

            case R.id.btn_buy:
                if (coinPairBean != null) {
                    coinPairBean.setBuyMode(true);
                    coinPairBean.setNeedSwitchTradeTab(true);
                    //IntentUtils.goTrade(this,coinPairBean);
//                ToastUtils.showShort("Kline Post buy");
                    finish();
                    EventBus.getDefault().postSticky(coinPairBean);
                }
                break;
            case R.id.btn_sell:
                if (coinPairBean != null) {
                    coinPairBean.setBuyMode(false);
                    coinPairBean.setNeedSwitchTradeTab(true);
//                    IntentUtils.goTrade(this,coinPairBean);
//                ToastUtils.showShort("Kline Post sell");
                    finish();
                    EventBus.getDefault().postSticky(coinPairBean);
                }
                break;

        }
    }

    private int lastIndexTab = -1;
    private int lastIndexLandTab = -1;

    private void swtichIndexTab(int indexTab, int indexLandTab) {
        if (lastIndexTab != -1) {
            viewFinder.textView(lastIndexTab).setTextColor(ContextCompat.getColor(this, CommonUtil.isBlackMode() ? R.color.dark_night : R.color.dark));
        }
        if (lastIndexLandTab != -1) {
            viewFinder.textView(lastIndexLandTab).setTextColor(ContextCompat.getColor(this, CommonUtil.isBlackMode() ? R.color.dark_night : R.color.dark));
        }
        viewFinder.textView(indexTab).setTextColor(ContextCompat.getColor(this, R.color.blue));
        viewFinder.textView(indexLandTab).setTextColor(ContextCompat.getColor(this, R.color.blue));
        lastIndexTab = indexTab;
        lastIndexLandTab = indexLandTab;
    }

    private int lastSubIndexTab = -1;
    private int lastSubIndexLandTab = -1;

    private void swtichSubIndexTab(int indexTab, int indexLandTab) {
        if (lastSubIndexTab != -1) {
            viewFinder.textView(lastSubIndexTab).setTextColor(ContextCompat.getColor(this, CommonUtil.isBlackMode() ? R.color.dark_night : R.color.dark));
        }
        if (lastSubIndexLandTab != -1) {
            viewFinder.textView(lastSubIndexLandTab).setTextColor(ContextCompat.getColor(this, CommonUtil.isBlackMode() ? R.color.dark_night : R.color.dark));
        }
        viewFinder.textView(indexTab).setTextColor(ContextCompat.getColor(this, R.color.blue));
        viewFinder.textView(indexLandTab).setTextColor(ContextCompat.getColor(this, R.color.blue));
        lastSubIndexTab = indexTab;
        lastSubIndexLandTab = indexLandTab;
    }

    /**
     * 切换K线图以及各种状态切换
     *
     * @param tabId
     * @param klineType
     */

    private void switchKline(int tabId, int klineType) {
        if (tabId == R.id.tab_depth) {
            if (isVerticalScreen) {
                isDepthTab = true;
            }
            /***深度**/
            if (currentTabId != R.id.tab_depth) {
                switchKlineTabIndicator(false);
                switchShowKlineTabView(false);
                viewPagerKline.setCurrentItem(0);
            } else {
                //二次点击不处理
            }
        } else {
            if (isVerticalScreen) {
                isDepthTab = false;
            }
            /**K线的tab情况下*******/
            if (tabId == R.id.tab_kline) {
                /****判断切换Tab情况下*********/
                if (currentTabId == R.id.tab_depth) {
                    //当前在深度图tab下
                    switchKlineTabIndicator(true);
                    switchShowKlineTabView(false);
                    /****默认是15分钟线***/
                    switchDefaultKline(currentKlineType);


                } else {
                    //当前在K线tab下 所以直接显示选择子K线tab
                    switchKlineTabIndicator(true);
                    switchShowKlineTabView(!currentShowKlineTab);
                }
            } else {
                swtichKlineTab(tabId);
                viewPagerKline.setCurrentItem(1);
                klineFragment.setKlineType(klineType);
                currentKlineType = klineType;

                switchShowKlineTabView(false);
            }

        }
        currentTabId = tabId;

    }

    /****默认是15分钟线
     * @param currentKlineType***/
    private void switchDefaultKline(int currentKlineType) {
        viewPagerKline.setCurrentItem(1);
        klineFragment.setKlineType(currentKlineType);
    }

    HashMap<Integer, TextView> klineTabMap = new HashMap<Integer, TextView>();
    HashMap<Integer, TextView> landTabMap = new HashMap<Integer, TextView>();

    private void swtichKlineTab(int tabId) {

//        tabTv.setTextColor(getResources().getColor(R.color.color_white));
        klineTabMap.put(tabId, viewFinder.textView(tabId));
        if (!klineTabMap.isEmpty()) {
            for (int id : klineTabMap.keySet()) {
                if (id == tabId) {
                    TextView tabTv = viewFinder.textView(tabId);
                    tabTv.setTextColor(getResources().getColor(R.color.blue));
                    if (viewFinder.textView(R.id.tab_kline_name) != null)
                        viewFinder.textView(R.id.tab_kline_name).setText(tabTv.getText().toString());
                } else {
                    viewFinder.textView(id).setTextColor(CommonUtil.isBlackMode() ? getResources().getColor(R.color.dark_night) : getResources().getColor(R.color.dark));
                }
            }
        }

    }

    private void swtichLandTab(int tabId) {

//        tabTv.setTextColor(getResources().getColor(R.color.color_white));
        landTabMap.put(tabId, (TextView) tabLandView.findViewById(tabId));
        if (tabId == R.id.tab_land_minutes) {
            tabLandMinutesIcon.setImageResource(R.mipmap.icon_arrow_up_blue);
        } else {
            tabLandMinutesIcon.setImageResource(R.mipmap.icon_arrow_up_gray);
        }
        if (!landTabMap.isEmpty()) {
            for (int id : landTabMap.keySet()) {
                if (id == tabId) {
                    TextView tabTv = tabLandView.findViewById(tabId);
                    tabTv.setTextColor(getResources().getColor(R.color.blue));
                } else {
                    TextView otherTab = tabLandView.findViewById(id);
                    otherTab.setTextColor(CommonUtil.isBlackMode() ? getResources().getColor(R.color.dark_night) : getResources().getColor(R.color.dark));
                }
            }
        }

    }

    /**
     * 切换显示K线tab选项视图
     */
    private void switchShowKlineTabView(boolean isShowKlineTab) {
        if (isShowKlineTab) {
            DebugLog.e("TAB", "TAB显示");
            viewFinder.find(R.id.tabLinear1).setVisibility(View.VISIBLE);
        } else {
            DebugLog.e("TAB", "TAB隐藏");
            viewFinder.find(R.id.tabLinear1).setVisibility(View.GONE);
        }
        currentShowKlineTab = isShowKlineTab;

    }

    /**
     * 切换tab底部颜色
     *
     * @param isKlineIndicator
     */
    private void switchKlineTabIndicator(boolean isKlineIndicator) {
        if (isKlineIndicator) {
            viewFinder.textView(R.id.tab_kline_name).setTextColor(getResources().getColor(R.color.blue));
            viewFinder.imageView(R.id.tab_kline_selctec_icon).setImageResource(R.mipmap.icon_arrow_down_blue);
            viewFinder.textView(R.id.tab_kline_depth).setTextColor(SkinColorUtil.getDark(this));
            viewFinder.find(R.id.tab_indicator_kline).setVisibility(View.VISIBLE);
            viewFinder.find(R.id.tab_indicator_depth).setVisibility(View.INVISIBLE);
        } else {
            viewFinder.textView(R.id.tab_kline_name).setTextColor(SkinColorUtil.getDark(this));
            viewFinder.imageView(R.id.tab_kline_selctec_icon).setImageResource(R.mipmap.icon_arrow_down_black);
            viewFinder.textView(R.id.tab_kline_depth).setTextColor(getResources().getColor(R.color.blue));
            viewFinder.find(R.id.tab_indicator_kline).setVisibility(View.INVISIBLE);
            viewFinder.find(R.id.tab_indicator_depth).setVisibility(View.VISIBLE);
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        boolean isLandScape = (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE);
        if (isLandScape && event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
            return false;
        } else {
            return super.onKeyUp(keyCode, event);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        RateAndLocalManager.GetInstance(KlineActivity.this).SetCurLocalKind(KlineActivity.this, RateAndLocalManager.GetInstance(KlineActivity.this).getCurLocalKind());
        //横竖屏变化通知
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            isVerticalScreen = false;
            if (isDepthTab) {
                //判断竖屏显示的深度图，则切换横屏时显示当前K线类型
                switchDefaultKline(currentKlineType);
            }
            tabLinear1.setVisibility(View.GONE);
            switchTopMarketView(false);
            updateViewStatus(View.GONE);
            viewFinder.find(R.id.tab_fullscreen).setVisibility(View.GONE);
            verticalScreen.setVisibility(View.VISIBLE);
            indexLandView.setVisibility(View.GONE);
            updateKlineTabLocation(false);
            tabLandView.setVisibility(View.VISIBLE);
        } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            isVerticalScreen = true;
            if (isDepthTab) {
                //判断竖屏显示的深度图，则切换回竖屏时显示回深度图
                switchDepthView();
            }
            switchTopMarketView(true);
            updateViewStatus(View.VISIBLE);
            viewFinder.find(R.id.tab_fullscreen).setVisibility(View.VISIBLE);
            verticalScreen.setVisibility(View.GONE);
            indexLandView.setVisibility(View.GONE);
            tabLandView.setVisibility(View.GONE);
            updateKlineTabLocation(true);
        }

    }

    private void switchDepthView() {
        switchKlineTabIndicator(false);
        switchShowKlineTabView(false);
        viewPagerKline.setCurrentItem(0);
    }

    /**
     * 切换头部行情view
     *
     * @param isVertical
     */
    private void switchTopMarketView(boolean isVertical) {


        if (isVertical) {
            if (topMarketViewLand.getParent() == klineLinear)
                klineLinear.removeView(topMarketViewLand);
            if (KlineUtils.isSymbolOfOption(coinPairBean.getCoinType()))
                //期权
                topOptionView.setVisibility(View.VISIBLE);
            else
                topMarketView.setVisibility(View.VISIBLE);
        } else {
            topMarketView.setVisibility(View.GONE);
            topOptionView.setVisibility(View.GONE);
            if (topMarketViewLand.getParent() != klineLinear)
                klineLinear.addView(topMarketViewLand, 0);
            updateCoinName();
        }

    }

    private void updateCoinName() {
        if (coinPairBean != null) {
            if (KlineUtils.isSymbolOfBB(coinPairBean.getCoinType())) {
                ((TextView) findViewById(R.id.coinPairName)).setText(baseTokenName + "/" + quoteTokenName);
            }else if(KlineUtils.isSymbolOfOption(coinPairBean.getCoinType())){
                //期权
                ((TextView) findViewById(R.id.coinPairName)).setText(coinPairBean.getSymbolName());
            }else if(KlineUtils.isSymbolOfFutures(coinPairBean.getCoinType())){
                //合约
                ((TextView) findViewById(R.id.coinPairName)).setText(coinPairBean.getSymbolName());
            }
        }
    }

    /**
     * 动态更新Kline tab展示位置
     */
    private void updateKlineTabLocation(boolean isVertical) {
        try {

            if (isVertical) {
                tabLinear.setVisibility(View.VISIBLE);

                if (tabLandView.getParent() == klineLinear)
                    klineLinear.removeView(tabLandView);
                //klineLinear.removeView(klineTabRela);
                //klineLinear.addView(klineTabRela, 3);
                tabLinear1LayoutParams.addRule(RelativeLayout.ALIGN_BOTTOM, 0);
                tabLinear1LayoutParams.addRule(RelativeLayout.ALIGN_TOP, R.id.viewPagerKline);
                tabLinear1.setLayoutParams(tabLinear1LayoutParams);
//            tabLinear.setBackgroundColor(getResources().getColor(R.color.color_bg_2));
            } else {
                tabLinear.setVisibility(View.GONE);

                //if(klineTabRela.getParent() == klineLinear)
                //  klineLinear.removeView(klineTabRela);
                //klineLinear.removeView(klineTabRela);
                if (tabLandView.getParent() != klineLinear)
                    klineLinear.addView(tabLandView);
//            klineLinear.addView(klineTabRela);
                //klineLinear.addView(tabLandView);
//            tabLinear1LayoutParams.addRule(RelativeLayout.ALIGN_TOP, 0);//移除rule
//            tabLinear1LayoutParams.addRule(RelativeLayout.ALIGN_BOTTOM, R.id.viewPagerKline);
//            tabLinear1.setLayoutParams(tabLinear1LayoutParams);
//            tabLinear.setBackgroundColor(getResources().getColor(R.color.font_color1));
            }
        } catch (Exception e) {
        }

        updateTabIdAndIndexId(isVertical);
    }

    /**
     * 切换tab和指标
     *
     * @param isVertical
     */
    private void updateTabIdAndIndexId(boolean isVertical) {
//        if (isVertical) {
//            tabTime = viewFinder.find(R.id.tab_time);
//            tabTime = viewFinder.find(R.id.tab_minute);
//        }else{
//            tabTime = viewFinder.find(R.id.tab_kline_time);
//        }
    }


    private void initKlineFragmentTab() {
        itemsKline = new ArrayList<>();
        Bundle bundle = new Bundle();
        bundle.putString(AppData.INTENT.SYMBOLS, coinPair);
        bundle.putString(AppData.INTENT.EXCHANGE_ID, exchangeId);
        bundle.putString(AppData.INTENT.MERGE_DIGITS, mergeDigitsStr);
        bundle.putSerializable(AppData.INTENT.COINPAIR, coinPairBean);
        //深度
        DepthViewFragment depthViewFragment = new DepthViewFragment();
        depthViewFragment.setArguments(bundle);
        //K线
        klineFragment = new KlineFragment();
        Bundle bundle1 = new Bundle();
        bundle1.putString(AppData.INTENT.SYMBOLS, coinPair);
        bundle1.putString(AppData.INTENT.EXCHANGE_ID, exchangeId);
        bundle1.putString(AppData.INTENT.MERGE_DIGITS, mergeDigitsStr);
        bundle1.putSerializable(AppData.INTENT.COINPAIR, coinPairBean);
        klineFragment.setArguments(bundle1);
        itemsKline.add(new Pair<String, Fragment>(getString(R.string.string_depth), depthViewFragment));
        //itemsKline.add(new Pair<String, Fragment>(getString(R.string.string_times), minimLineFragment));
        itemsKline.add(new Pair<String, Fragment>(getString(R.string.string_kline), klineFragment));
        viewPagerKline.setAdapter(new KlineAdapter(getSupportFragmentManager()));
//        tab.setupWithViewPager(viewPager);
//        tab.setTabTextColors(getResources().getColor(R.color.color_white),getResources().getColor(R.color.color_black));
//        tab.setTabMode(TabLayout.MODE_SCROLLABLE);
//        tab.setTabGravity(TabLayout.GRAVITY_CENTER);
        if (isDefaultSeeDepth) {
            //交易深度图点击进来 默认直接看深度图
            switchKline(R.id.tab_depth, CHART_TYPE_NOT_KLINE);
        } else {
            //默认K线
            viewPagerKline.setCurrentItem(1);
        }
    }

    private void initOrderFragmentTab() {
        items = new ArrayList<>();
        bookListFragment = new BookListFragment();
        DealPriceFragment dealPriceFragment = new DealPriceFragment();
        TokenBriefIntroductionFragment tokenBriefIntroductionFragment = new TokenBriefIntroductionFragment();
        Bundle bundle = new Bundle();
//        bundle.putString(AppData.INTENT.EXCHANGE_ID, exchangeId);
//        bundle.putString(AppData.INTENT.SYMBOLS, coinPair);
//        bundle.putString(AppData.INTENT.MERGE_DIGITS, mergeDigitsStr);
        bundle.putSerializable(AppData.INTENT.SYMBOLS, coinPairBean);
        bookListFragment.setArguments(bundle);
        dealPriceFragment.setArguments(bundle);
        tokenBriefIntroductionFragment.setArguments(bundle);
        items.add(new Pair<String, Fragment>(getString(R.string.string_entrust_order), bookListFragment));
        items.add(new Pair<String, Fragment>(getString(R.string.string_latest_deal), dealPriceFragment));
        if (KlineUtils.isSymbolOfBB(coinPairBean.getCoinType())) {
            //只有币币的K线有币种简介
            items.add(new Pair<String, Fragment>(getString(R.string.string_brief_introduction), tokenBriefIntroductionFragment));
        }
        viewPager.setAdapter(new OrderAdapter(getSupportFragmentManager()));
        tab.setupWithViewPager(viewPager);
//        tab.setTabTextColors(getResources().getColor(R.color.color_white), getResources().getColor(R.color.color_black));
        tab.setTabMode(TabLayout.MODE_FIXED);
        tab.setTabGravity(TabLayout.GRAVITY_FILL);
        tab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                currentOrderTabPosition = tab.getPosition();
                if (currentOrderTabPosition == 0) {
//                    viewFinder.find(R.id.title_decimal_num).setVisibility(View.VISIBLE);
                    entrustHeader.setVisibility(View.VISIBLE);
                    latestHeader.setVisibility(View.GONE);
                    appBarLayoutParams.height = appBarHeight + PixelUtils.dp2px(HEIGHT_ENTRUST_HEADER);
                    appBar.setLayoutParams(appBarLayoutParams);
                    appBar.requestFocus();
                } else if(currentOrderTabPosition == 1){
//                    viewFinder.find(R.id.title_decimal_num).setVisibility(View.GONE);
                    entrustHeader.setVisibility(View.GONE);
                    latestHeader.setVisibility(View.VISIBLE);
                    appBarLayoutParams.height = appBarHeight + PixelUtils.dp2px(HEIGHT_LATEST_HEADER);
                    appBar.setLayoutParams(appBarLayoutParams);
                    appBar.requestFocus();
                }else{
                    entrustHeader.setVisibility(View.GONE);
                    latestHeader.setVisibility(View.GONE);
                    appBarLayoutParams.height = appBarHeight;
                    appBar.setLayoutParams(appBarLayoutParams);
                    appBar.requestFocus();
                    appBar.setLifted(false);
                }

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        CommonUtil.setUpIndicatorWidthByReflex3(tab, 15, 15);
    }

    @Override
    public void showTicker(TickerBean data) {
        if (data != null) {
            currentTicker = data;
            float riseFallAmount = KlineUtils.calRiseFallAmountFloat(data.getC(), data.getO());
            ((TextView) findViewById(R.id.latestPrice)).setText(NumberUtils.roundFormatDown(data.getC(), quoteDigit));
            ((TextView) findViewById(R.id.option_latestPrice)).setText(NumberUtils.roundFormatDown(data.getC(), quoteDigit));
            if (coinPairBean!=null && coinPairBean.getCoinType()== COIN_TYPE.COIN_TYPE_PERPETUAL_CONTRACT.getCoinType() && coinPairBean.baseTokenFutures!=null) {
                //合约 使用displayTokenId
                String legalMoney = RateDataManager.CurRatePrice(coinPairBean.baseTokenFutures.getDisplayTokenId(), data.getC());
                legalMoney = RateDataManager.getShowLegalMoney(legalMoney, AppData.DIGIT_LEGAL_MONEY);
                ((TextView) findViewById(R.id.latestPrice2)).setText("≈" + legalMoney);
            }else{

                String legalMoney = RateDataManager.CurRatePrice(quoteToken, data.getC());
                legalMoney = RateDataManager.getShowLegalMoney(legalMoney, AppData.DIGIT_LEGAL_MONEY);
                ((TextView) findViewById(R.id.latestPrice2)).setText("≈" + legalMoney);
                ((TextView) findViewById(R.id.option_latestPrice2)).setText("≈" + legalMoney);
            }
            ((TextView) findViewById(R.id.highPrice)).setText(NumberUtils.roundFormatDown(data.getH(), quoteDigit));
            ((TextView) findViewById(R.id.option_highPrice)).setText(NumberUtils.roundFormatDown(data.getH(), quoteDigit));
            ((TextView) findViewById(R.id.lowPrice)).setText(NumberUtils.roundFormatDown(data.getL(), quoteDigit));
            ((TextView) findViewById(R.id.option_lowPrice)).setText(NumberUtils.roundFormatDown(data.getL(), quoteDigit));
//            ((TextView) findViewById(R.id.riseFallAmount)).setText(NumberUtils.roundFormatDown(riseFallAmount,2));
            if (isVerticalScreen) {
                ((TextView) findViewById(R.id.riseFallRatio)).setText(KlineUtils.calRiseFallRatio(data.getC(), data.getO()));
                KlineUtils.setMarketViewBgColor(riseFallAmount, findViewById(R.id.riseFallRatio));
//                ((TextView) findViewById(R.id.riseFallRatio)).setTextColor(SkinColorUtil.getWhite(this));
                ((TextView) findViewById(R.id.option_riseFallRatio)).setText(KlineUtils.calRiseFallRatio(data.getC(), data.getO()));
                KlineUtils.setMarketViewBgColor(riseFallAmount, findViewById(R.id.option_riseFallRatio));
//                ((TextView) findViewById(R.id.option_riseFallRatio)).setTextColor(SkinColorUtil.getWhite(this));
            } else {
                ((TextView) findViewById(R.id.riseFallRatio)).setText("(" + KlineUtils.calRiseFallRatio(data.getC(), data.getO()) + ")");
                findViewById(R.id.riseFallRatio).setBackgroundColor(getResources().getColor(R.color.transparent));
                KlineUtils.setMarketViewColor(riseFallAmount, (TextView) findViewById(R.id.riseFallRatio));
            }

            ((TextView) findViewById(R.id.volume)).setText(NumberUtils.roundFormatDown(data.getV(), coinPairBean.getCoinType()==COIN_TYPE.COIN_TYPE_PERPETUAL_CONTRACT.getCoinType()?AppData.DIGIT_24H_AMOUNT_CONTACT : AppData.DIGIT_24H_AMOUNT));
            ((TextView) findViewById(R.id.option_volume)).setText(NumberUtils.roundFormatDown(data.getV(), AppData.DIGIT_24H_AMOUNT) + getString(R.string.string_option_unit));

            KlineUtils.setMarketViewColor(riseFallAmount, (TextView) findViewById(R.id.latestPrice));
            KlineUtils.setMarketViewColor(riseFallAmount, (TextView) findViewById(R.id.latestPrice2));
            try {
                if (KlineUtils.isSymbolOfOption(coinPairBean.getCoinType())) {
                    //期权
                    double ratio = NumberUtils.div(data.getC(), coinPairBean.baseTokenOption.maxPayOff);
                    ((TextView) findViewById(R.id.option_lever)).setText(NumberUtils.roundFormatDown(ratio, 2) + "X");
                }
            } catch (Exception e) {

            }

        }
    }

    @Override
    public void getTickerFailed(String msg) {

    }

    @Override
    public void setCurrentPriceDigits(PriceDigits response) {
        if (response != null) {
            digitsList = response.getArray();
            if (!digitsList.isEmpty()) {
                String digits = digitsList.get(0).getDigits();
                EventBus.getDefault().post(new PriceDigitsEvent(digits));
            }
        }

    }

    @Override
    public String getExchangeId() {
        return exchangeId;
    }

    @Override
    public String getSymbols() {
        return coinPair;
    }

    /**
     * 更新横竖屏页面显示元素
     *
     * @param isVisible
     */
    private void updateViewStatus(int isVisible) {

        topBar.setVisibility(isVisible);
//        topMarketView.setVisibility(isVisible);
        tab.setVisibility(isVisible);
        viewPager.setVisibility(isVisible);
        buysellLinear.setVisibility(isVisible);
//        int chartViewHeight = PixelUtils.getScreenHeight() - tabLinear.getHeight()-topMarketViewLand.getHeight()-marketDividerView.getHeight();
        int truthLandHeight = PixelUtils.getScreenHeight() > PixelUtils.getScreenWidth() ? PixelUtils.getScreenWidth() : PixelUtils.getScreenHeight();
        int chartViewHeight = truthLandHeight - tabLinear.getHeight() - PixelUtils.dp2px(45) - marketDividerView.getHeight();
//        int chartViewHeight = PixelUtils.getScreenHeight()-PixelUtils.getStatusBarHeight(this)-tabLinear.getHeight();
//        DebugLog.i("screenHeight:" + (PixelUtils.getScreenHeight() - PixelUtils.getStatusBarHeight(this)) + "  " + PixelUtils.getStatusBarHeight(this));
//        DebugLog.i("screenHeight:" +PixelUtils.getScreenHeight() +" w: "+PixelUtils.getScreenWidth());
        //屏幕滚动 appbar top改变 造成切换屏幕 Kline视图上移
        int top = appBar.getTop();
//        ToastUtils.showShort("top: "+top+"  "+appBarLayoutParams.topMargin);
        if (isVisible == View.GONE) {//横屏
            entrustHeader.setVisibility(View.GONE);
            latestHeader.setVisibility(View.GONE);
            appBarLayoutParams.height = truthLandHeight;
//            DebugLog.i("screenHeight1:" +PixelUtils.getScreenHeight() +"  w: "+PixelUtils.getScreenWidth());
//            appBarLayoutParams.height = PixelUtils.getScreenHeight()-PixelUtils.getStatusBarHeight(this);
            //屏幕滚动 appbar top改变 造成切换屏幕 Kline视图上移
            appBarLayoutParams.topMargin = -top;
            appBar.setLayoutParams(appBarLayoutParams);
            forbidAppBarScroll(true);

            indexLandViewLayoutParams.height = chartViewHeight - PixelUtils.dp2px(10);
            indexLandView.setLayoutParams(indexLandViewLayoutParams);
            layoutParamsViewPagerKline.height = chartViewHeight;
            viewPagerKline.setLayoutParams(layoutParamsViewPagerKline);
            requestFullScreen(true);
        } else {
            appBarLayoutParams.topMargin = -top;
            if (currentOrderTabPosition == 0) {
                entrustHeader.setVisibility(View.VISIBLE);
                latestHeader.setVisibility(View.GONE);
                appBarLayoutParams.height = appBarHeight + PixelUtils.dp2px(HEIGHT_ENTRUST_HEADER);
                appBar.setLayoutParams(appBarLayoutParams);
            } else {
                latestHeader.setVisibility(View.VISIBLE);
                entrustHeader.setVisibility(View.GONE);
                appBarLayoutParams.height = appBarHeight + PixelUtils.dp2px(HEIGHT_LATEST_HEADER);
                appBar.setLayoutParams(appBarLayoutParams);
            }
            forbidAppBarScroll(false);

            layoutParamsViewPagerKline.height = PixelUtils.dp2px(VIEWPAGER_KLINE_HEIGHT_DEFAULT);
            viewPagerKline.setLayoutParams(layoutParamsViewPagerKline);
            requestFullScreen(false);
        }

        showTicker(currentTicker);
    }


    /**
     * 请求是否全屏显示
     *
     * @param isFullScrren
     */
    private void requestFullScreen(boolean isFullScrren) {
        if (isFullScrren) {
            // 隐藏标题栏
            //requestWindowFeature(Window.FEATURE_NO_TITLE);//适用于活动继承Activity
            // 隐藏状态栏
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }

    }

    @Override
    public void OnIndexChanged() {
        if (coinPairBean != null && coinPairBean.baseTokenOption != null) {

            String indexData = NumberUtils.roundFormatDown(AssetUtilsManager.GetInstance().getSymbolIndexOfOption(coinPairBean.baseTokenOption.indexToken), quoteDigit);
            viewFinder.textView(R.id.option_exercise_point).setText(indexData);
        }
    }

    /**
     * 订单Adapter
     */
    private class OrderAdapter extends FragmentPagerAdapter {

        public OrderAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return items.get(position).second;
        }

        @Override
        public int getCount() {
            return items.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return items.get(position).first;
        }
    }


    /**
     * K线Adapter
     */
    private class KlineAdapter extends FragmentPagerAdapter {

        public KlineAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return itemsKline.get(position).second;
        }

        @Override
        public int getCount() {
            return itemsKline.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return itemsKline.get(position).first;
        }
    }

    /**
     * 禁止AppbarLayout滑动
     *
     * @param forbid
     */
    private void forbidAppBarScroll(boolean forbid) {
        if (forbid == forbidAppBarScroll) {
            return;
        }
        if (forbid) {
            forbidAppBarScroll = true;
            if (ViewCompat.isLaidOut(appBar)) {
                setAppBarDragCallback(new AppBarLayout.Behavior.DragCallback() {

                    @Override
                    public boolean canDrag(@NonNull AppBarLayout appBarLayout) {
                        return false;
                    }
                });
            } else {
                appBar.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                            appBar.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                        } else {
                            appBar.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                        }
                        setAppBarDragCallback(new AppBarLayout.Behavior.DragCallback() {

                            @Override
                            public boolean canDrag(@NonNull AppBarLayout appBarLayout) {
                                return false;
                            }
                        });
                    }
                });
            }
        } else {
            forbidAppBarScroll = false;
            if (ViewCompat.isLaidOut(appBar)) {
                setAppBarDragCallback(null);
            } else {
                appBar.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                            appBar.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                        } else {
                            appBar.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                        }
                        setAppBarDragCallback(null);
                    }
                });
            }
        }
    }


    /**
     * 设置AppBarLayout拖动回调
     *
     * @param dragCallback
     */
    private void setAppBarDragCallback(AppBarLayout.Behavior.DragCallback dragCallback) {
        /*LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) appBar.getLayoutParams();
        AppBarLayout.Behavior behavior = (AppBarLayout.Behavior) params.getBehavior();
        behavior.setDragCallback(dragCallback);*/
    }

    private void getSettleStatus() {
        if (coinPairBean != null) {
            OptionApi.RequestOptionStatus(coinPairBean.getSymbolId(), new SimpleResponseListener<OptionSymbolStatusBean>() {
                @Override
                public void onSuccess(OptionSymbolStatusBean response) {
                    super.onSuccess(response);
                    if (CodeUtils.isSuccess(response, false)) {
                        List<OptionSymbolStatusBean.OptionSymbolStatus> data = response.array;
                        if (data != null) {
                            for (OptionSymbolStatusBean.OptionSymbolStatus bean : data) {
                                if (bean != null && !TextUtils.isEmpty(coinPairBean.getSymbolId()) && coinPairBean.getSymbolId().equalsIgnoreCase(bean.symbolId)) {
                                    mOptionSymbolStatus = bean;
                                }
                            }
                        }
                    }
                }
            });
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        DialogUtils.showDialogOneBtn(this, getString(R.string.string_reminder), getString(R.string.file_read_write_permission_hint), getString(R.string.string_i_know), false, new DialogUtils.OnButtonEventListener() {
            @Override
            public void onConfirm() {
                ToastUtils.showShort(getString(R.string.string_share_failed));
            }

            @Override
            public void onCancel() {
                ToastUtils.showShort(getString(R.string.string_share_failed));
            }
        });
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (requestCode == WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE) {
            //TODO 权限请求成功
            //ToastUtils.showLong("权限请求成功");
            shareDialogAction();
        } else {
            Toast.makeText(this, "request permission fail!", Toast.LENGTH_SHORT).show();
        }
    }
}
